import React, { Component } from 'react';

import { Form, Input, Button, Row, Col, message } from 'antd';
import { connect } from 'dva';
import GetYCodeFormItem from '../../components/GetYCodeFormItem';
import { email as emailReg } from '@/utils/regexp';
const FormItem = Form.Item;

@Form.create()
@connect(({ loading,userCenter: { information } }) => ({
  loading: loading.effects['bindEmail/setBindEmail'],
  information,
}))
class BindEmail extends Component {
  handleSubmit = e => {
    e.preventDefault();
    const { form, dispatch, changeStatus } = this.props;
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const emailData = {};
        emailData.email = values.email;
        emailData.code = values.validCode
        dispatch({
          type: 'bindEmail/setBindEmail',
          payload: emailData,
        })
          .then(msg => {
            changeStatus(true);
          })
          .catch(errMsg => {
            message.error(errMsg);
          });
      }
    });
  };

  componentDidMount() {
    this.props.dispatch({
      type: 'userCenter/queryUserInformation',
    });
  }

  render() {
    const {
      form: { getFieldDecorator },
      form,
      loading,
      information
    } = this.props;
    console.log('----------->',information)
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
      },
    };
    return (
      <Form onSubmit={this.handleSubmit}>
        <Row>
          <Col span={8}>
            <FormItem label="邮箱" {...formItemLayout}>
              {getFieldDecorator('email', {
                initialValue: information&&information.email,
                rules: [
                  {
                    required: true,
                    message: "请输入邮箱地址!"
                  },
                  {
                    message: "请输入正确的邮箱地址!",
                    pattern: emailReg
                  }
                ],
              })(<Input placeholder="邮箱地址" />)}
            </FormItem>
          </Col>
        </Row>

        <GetYCodeFormItem form={form} validField="email" type ='email' formItemLayout={formItemLayout} />

        <Row>
          <Col span={8} offset={2}>
            <Button type="primary" htmlType="submit" disabled={loading}>
              {loading ? '请稍后' : '下一步'}
            </Button>
          </Col>
        </Row>
      </Form>
    );
  }
}
export default BindEmail;
